<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Utils\AppResult;
use App\Utils\Control\AuthUser;
use App\Utils\LogUtil;
use Hyperf\Coroutine\Coroutine;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class ApiSign implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @var HttpResponse
     */
    protected $response;

    public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request)
    {
        $this->container = $container;
        $this->response  = $response;
        $this->request   = $request;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        //验证登录
        if (!AuthUser::getInstance()->check()) {
            return $this->response400();
        }

        // 根据具体业务判断逻辑走向
        return $handler->handle($request);
    }

    /**
     * @param string $message
     * @param $result
     * @return ResponseInterface
     */
    private function response400(string $message = '未登录，令牌失效，请稍后重试！', $result = null): ResponseInterface
    {
        return AppResult::response400($message, $result);
    }
}